package me.xiaosiqi.server_info.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jdk.nashorn.internal.ir.CallNode;
import lombok.extern.slf4j.Slf4j;
import me.xiaosiqi.server_info.comm.BaseResponse;
import me.xiaosiqi.server_info.comm.Command;
import me.xiaosiqi.server_info.mapper.CommandMapper;
import me.xiaosiqi.server_info.tool.IpTool;
import me.xiaosiqi.server_info.tool.ServerChanService;
import me.xiaosiqi.server_info.tool.ServerDescTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;

/**
 * @Author: xiaosiqi
 * @date 2021/11/11 10:49
 */
@Slf4j
@RestController
@RequestMapping("/command")
public class CommandController {

    @Autowired
    private CommandMapper commandMapper;

    @PostMapping("/cmdList")
    public BaseResponse cmdList() {
        List<Command> commands = commandMapper.selectList(null);
        return BaseResponse.ok(commands);
    }
    @PostMapping("/cmd")
    public BaseResponse cmd(@RequestParam Integer id) {
        try {
            Command command = commandMapper.selectById(id);
            if (null == command) {
                return BaseResponse.error("未知命令");
            }
            //执行的脚本命令（注意：加参数的话，.sh和参数之间保留一个空格）
            Process proc = Runtime.getRuntime().exec(command.getCmd());
            //获取脚本执行的得到的结果并缓存
            BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String str;
            StringBuilder stringBuilder = new StringBuilder();
            //读取数据
            while ((str = reader.readLine()) != null) {
                stringBuilder.append(str).append("\n");
            }
            reader.close();
            proc.waitFor();
            return BaseResponse.ok(stringBuilder);
        } catch (Exception e) {
            return BaseResponse.error(e.getMessage());
        }
    }
}